package cn.wxxyhw.server;

import cn.wxxyhw.Dao.MessageDao;
import cn.wxxyhw.Dao.UserDao;
import cn.wxxyhw.Entity.Message;
import cn.wxxyhw.Util.DateFormateUtil;
import cn.wxxyhw.Util.SocketUtil;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: 洪稳
 * @Date: 2019/6/9
 */


@ServerEndpoint("/socket/{myId}/{myImage}/{youId}")
public class MyWebSocketServer {
    private static MessageDao messageDao = new MessageDao();
    private static UserDao userDao = new UserDao();
    /*群聊*/
    private static Map<String, List<SocketUtil>> qunChat = new HashMap<>(); //key->群id value ->群成员
    private static Map<String,SocketUtil> myInfo = new HashMap<>(); //key->个人ID,value->个人的信息
    private static Map<String,String> my = new HashMap<>(); //value->id key->sessionID
    private static Map<String,String> idQunId = new HashMap<>(); //key ->个人id value->群id
    /*私聊*/
    private static Map<String, SocketUtil> map = new HashMap<>(); //key => mid-yId ,value => object
    private static Map<String,String> sessions = new HashMap<>(); //key => sessionId,value => mId-yId
    @OnClose
    public void close(Session session){
        if (my.get(session.getId())!=null){ //群聊
            String id = my.get(session.getId());
            my.remove(session.getId());
            SocketUtil socketUtil = myInfo.get(id);
            String qid = idQunId.get(id);
            qunChat.get(qid).remove(socketUtil);
            myInfo.remove(id);
            idQunId.remove(id);
        }else {
            String id = sessions.get(session.getId());
            sessions.remove(session.getId());
            map.remove(id);
        }
    }

    @OnOpen
    public void open(Session session, @PathParam("myId") String myId,
                     @PathParam("myImage") String myImage,
                     @PathParam("youId") String youId){

        SocketUtil socketUtil = new SocketUtil();
        socketUtil.setMyImage(myImage);
        socketUtil.setSession(session);
        socketUtil.setMyName(userDao.getUserNameById(myId));
        if (youId.length()==4){/*当为群聊连接时，youId为群id*/
            myInfo.put(myId,socketUtil);//保存我的信息
            my.put(session.getId(),myId);//连接管道id与个人id结合
            if (qunChat.get(youId)==null){ //当群id不存在创建群聊
                qunChat.put(youId, new LinkedList<SocketUtil>());
            }
            qunChat.get(youId).add(socketUtil); //群员信息加入群集合
            idQunId.put(myId,youId); //个人id与群id
        }else { /*私聊连接*/
            map.put(myId+"-"+youId,socketUtil);  //保存我的id以及对应的信息
            sessions.put(session.getId(),myId+"-"+youId);//保存id对应的sessionId;
        }


    }

    @OnMessage
    public void message(Session session,String message){
        Message msg = new Message();
        msg.setContent(message);
        if (sessions.get(session.getId())==null){ //判断是否为群聊
            String mid = my.get(session.getId());
            msg.setFromId(mid);
            String qid = idQunId.get(my.get(session.getId()));
            msg.setToId(qid);
            String image = myInfo.get(mid).getMyImage();
            String name = myInfo.get(mid).getMyName();
            messageBorder(qid,message,session,image,name); //消息群发
        }else {//私聊情况
            String myId = sessions.get(session.getId());
            String[] ids = myId.split("-");
            SocketUtil friendSocket = map.get(ids[1] + "-" + ids[0]);
            //保存消息
            msg.setFromId(ids[0]);
            msg.setToId(ids[1]);
            if (friendSocket == null) { //表示用户不在线
                msg.setRead(0); //0表示未读
            } else {
                Session session1 = friendSocket.getSession();
                msg.setRead(1); //1表示已读
                try {
                    session1.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        msg.setDate(DateFormateUtil.getDateFormat().format(new Date()));
        messageDao.save(msg);
    }

    /**
     * 消息群发
     * @param qid  群id
     * @param message  消息
     */
    public void messageBorder(String qid,String message,Session session,String image,String name){
        List<SocketUtil> socketUtils = qunChat.get(qid).stream().filter(socket -> !socket.getSession().equals(session)).collect(Collectors.toList());
        for (SocketUtil socketUtil : socketUtils){
            String msg = "{\"message\":\""+message+"\",\"image\":\""+image+"\",\"name\":\""+name+"\"}";
            try {
                socketUtil.getSession().getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
